package com.zhida.common.interceptor;

//import com.alibaba.fastjson.JSON;

import com.fasterxml.jackson.databind.JsonNode;
import com.zhida.common.context.UserContext;
import com.zhida.common.entity.TokenPassJson;
import com.zhida.common.utils.ObjectUtil;
import com.zhida.common.utils.TokenProcessor;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

import static com.zhida.common.utils.StaticKeyUtil.TOKEN_KEY;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            handleAuthenticationFailure(response, "认证失败，请先登录");
            return false;
        }
        int result = TokenProcessor.verify(token);
        if (result != 1) {
            handleAuthenticationFailure(response, "用户登录信息异常，请重新登陆");
            return false;
        }

        //  服务器中是否存在该用户token
        String userKey = TOKEN_KEY + TokenProcessor.getUserByToken(token);
        String userInfo = redisTemplate.opsForValue().get(userKey);
        if (StringUtils.isBlank(userInfo)) {
            handleAuthenticationFailure(response, "登陆信息失效，请重新登陆");
            return false;
        }

        //  请求的token和服务器中的token是否一致
        JsonNode jsonNode = ObjectUtil.JsonStr2Object(userInfo);
        if (!jsonNode.get("token").asText().equals(token)){
            handleAuthenticationFailure(response, "认证失败，请重新登陆");
            return false;
        }

        // 认证成功，将用户信息放入ThreadLocal
        UserContext.setUser(TokenProcessor.getUserByToken(token));
        System.out.println("通过拦截器");
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 4.清除用户信息
        UserContext.clear();
    }

    private void handleAuthenticationFailure(HttpServletResponse response, String message) throws IOException {
        TokenPassJson json = new TokenPassJson();
        json.setResult(0); // 假设0表示验证失败
        json.setMessage(message);
        json.setCode(500);
        response.getWriter().append(ObjectUtil.Object2JsonStr(json));
        System.out.println("认证失败，未通过拦截器");
    }
}
